package com.xueyu.file;

import javax.servlet.*;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

public class MyFilter implements Filter {
    public void destroy() {
    }
/*
* 设置前后端分离的跨域配置
* 过滤器必须在web.xml文件中配置
* */
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws ServletException, IOException {
        // 响应参数格式设置
        request.setCharacterEncoding("UTF-8");
        response.setCharacterEncoding("UTF-8");
        //response.setContentType("application/json");
        System.out.println("==========");

        HttpServletResponse response1 = (HttpServletResponse) response;
        /* 允许跨域的主机地址，前端接口地址 */
        response1.setHeader("Access-Control-Allow-Origin", "http://localhost:8080");
//        response1.setHeader("Access-Control-Allow-Origin", "*");
        /* 允许跨
        域的请求方法GET, POST, HEAD 等 */
        response1.setHeader("Access-Control-Allow-Methods", "GET,POST,PUT,DELETE,OPTIONS,HEAD");
        /* 重新预检验跨域的缓存时间 (s) */
        response1.setHeader("Access-Control-Max-Age", "3600");
        /* 允许跨域的请求头 */
        response1.setHeader("Access-Control-Allow-Headers", "*");
        /* 是否携带cookie */
        response1.setHeader("Access-Control-Allow-Credentials", "true");
        chain.doFilter(request, response1);
    }
    public void init(FilterConfig config) throws ServletException {

    }

}
